<template>
  <div class="css-slider-viewport">
    <div ref="slider" class="css-slider-holder"
         @mousedown="handleMouseDown"
         @mouseleave="handleMouseLeave"
         @mousemove="handleMouseMove"
         @mouseup="handleMouseUp">
      <div
          :style="{
'--visible-cols': visibleCols,
'--col-gap': '20px',
'--col-size': `calc((100% - var(--col-gap) * (var(--visible-cols) - 1)) / var(--visible-cols))`
}"
          class="grid grid--slider slider"
      >
        <aplusmax-home-good
            v-for="(goods, index) in itemsComputed"
            :id="`grid_slider_active_${index}`"
            :key="index"
            :goods="goods"
            :tag="false">
        </aplusmax-home-good>
      </div>
    </div>
  </div>
  <aplusmax-select
      :active="active"
      :count="items?.length || 0"
      :next="slide_right"
      :prev="slide_left"
      :slide_position="slide_position">
  </aplusmax-select>
</template>

<script lang='ts' setup>
import {defineProps, defineEmits, defineExpose, reactive, computed, ref, onMounted, onUnmounted} from 'vue'
import {goodsRandom} from "../../../api/goods";

defineProps({})
const slider = ref<HTMLElement | null>(null)
const active = ref(1)

const getVisibleCols = () => {
  if (window.innerWidth < 768) return 2
  if (window.innerWidth < 1024) return 3
  return 4
}

const visibleCols = ref(getVisibleCols())

let items = ref([])
// 加载商品
const getRandomGoods = () => {
  const payload = {
    is_new: 1,
    split:4
  }
  goodsRandom(payload).then((res) => {
    items.value = res.data
    console.log(items.value, "+++++++++++")
  }).catch((err) => {
    console.log(err)
  });
}
getRandomGoods()

const itemsComputed = computed(() => {
  return items.value.flat()
})

const handleResize = () => {
  const newCols = getVisibleCols()
  if (newCols !== visibleCols.value) {
    visibleCols.value = newCols
    active.value = 1 // 重置到第一页
  }
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

const translateX = ref(0)

const slide_position = (position: number) => {
  const container = slider.value;
  if (!container || !itemsComputed.value.length) return;

  // 计算每页商品数量和总页数
  const itemsPerPage = visibleCols.value;
  const totalPages = Math.ceil(itemsComputed.value.length / itemsPerPage);

  // 确保目标位置在有效范围内
  if (position < 1 || position > totalPages) return;

  active.value = position;

  // 计算目标元素的索引位置
  const targetIndex = (position - 1) * itemsPerPage;
  const targetElement = document.getElementById(`grid_slider_active_${targetIndex}`);

  if (targetElement) {
    // 添加平滑滚动效果
    container.scrollTo({
      left: targetElement.offsetLeft,
      behavior: 'smooth'
    });
  } else {
    // 回退方案：如果找不到目标元素，使用页面宽度计算
    container.scrollTo({
      left: (position - 1) * container.offsetWidth,
      behavior: 'smooth'
    });
  }
}

const slide_right = () => {
  if (!itemsComputed.value.length) return;

  // 计算总页数
  const totalPages = Math.ceil(itemsComputed.value.length / visibleCols.value);

  if (active.value < totalPages) {
    slide_position(active.value + 1);
  }
};

const slide_left = () => {
  if (active.value > 1) {
    slide_position(active.value - 1);
  }
};

const isDragging = ref(false)
const startX = ref(0)
const startScrollLeft = ref(0)
const dragDirection = ref<"left" | "right" | null>(null) // 新增：跟踪拖拽方向
let animationId = ref<number | null>(null)

const handleMouseDown = (e: MouseEvent) => {
  if (!slider.value) return
  isDragging.value = true
  dragDirection.value = null // 重置方向
  startX.value = e.pageX - slider.value.offsetLeft
  startScrollLeft.value = slider.value.scrollLeft
  slider.value.style.cursor = 'grabbing'
}

const handleMouseMove = (e: MouseEvent) => {
  if (!isDragging.value || !slider.value) return
  e.preventDefault()

  // 计算当前鼠标位置和移动方向
  const currentX = e.pageX - slider.value.offsetLeft
  const deltaX = currentX - startX.value

  // 确定拖拽方向
  if (deltaX > 5 && dragDirection.value !== "right") {
    dragDirection.value = "right" // 向右拖拽
  } else if (deltaX < -5 && dragDirection.value !== "left") {
    dragDirection.value = "left" // 向左拖拽
  }

  if (animationId.value) {
    cancelAnimationFrame(animationId.value)
  }

  animationId.value = requestAnimationFrame(() => {
    const walk = deltaX * 2 // 控制滑动速度
    slider.value!.scrollLeft = startScrollLeft.value - walk
  })
}

const handleMouseUp = () => {
  if (!slider.value) return
  isDragging.value = false

  if (animationId.value) {
    cancelAnimationFrame(animationId.value)
    animationId.value = null
  }

  slider.value.style.cursor = 'grab'

  // 根据拖拽方向更新页码
  if (dragDirection.value === "left") {
    // 向左滑动：下一页
    slide_right()
  } else if (dragDirection.value === "right") {
    // 向右滑动：上一页
    slide_left()
  }

  // 重置方向
  dragDirection.value = null
}

const handleMouseLeave = () => {
  // 鼠标离开时执行与松开鼠标相同的操作
  handleMouseUp()
}

const emit = defineEmits([])

defineExpose({})
</script>

<style lang='less' scoped>

.slider {
  display: flex;
  transition: transform 0.5s ease;
}
.css-slider-viewport{
  width: 100%;
  .css-slider-holder{
    overflow: hidden;
    //overflow-x: auto;
    scroll-behavior: smooth;
    scroll-snap-type: x mandatory;
    cursor: grab;
    user-select: none; // 防止拖动时选中文本

    --visible-cols: 4;
    --col-gap: 26px;
    --col-size: calc( (100% - var(--col-gap) * (var(--visible-cols) - 1)) / var(--visible-cols) );
    .grid--slider{
      grid-auto-flow: column;
      grid-template-columns: calc(var(--col-size));
      grid-auto-columns: calc(var(--col-size));
      position: relative;
    }
    .grid{
      display: grid;
      grid-gap: var(--col-gap);
      user-select: none; // 防止商品文字被选中
    }
    aplusmax-home-good {
      user-select: none; // 防止商品组件内文字被选中
    }
    .grid_slider_active {
      scroll-snap-align: start;
    }
  }
}

.product{
  display: flex;
  flex-direction: column;
  overflow: visible;
}
.css-slide--snap{
  scroll-snap-align: start;
}
.card{
  --border-width-cards: 1px;
  --border-radius-cards: 10px;
  --border-width-buttons: 1px;
  --border-radius-buttons: 30px;
  --border-width-forms: 1px;
  --border-radius-forms: 5px;
  --shadow-x-cards: 0px;
  --shadow-y-cards: 0px;
  --shadow-blur-cards: 0px;
  border: solid var(--border-width-cards) #e1e1e1;
  border-radius: var(--border-radius-cards);
  overflow: hidden;
  background-color: #ffffff;
  position: relative;
  color: #1d1d1d;
  box-shadow: var(--shadow-x-cards) var(--shadow-y-cards) var(--shadow-blur-cards) rgba(0,0,0,0);
  margin-bottom: calc(var(--shadow-y-cards) + var(--shadow-blur-cards));
  margin-inline-end: calc(var(--shadow-x-cards) + var(--shadow-blur-cards));
}
</style>